<template>
  <div class="settlement-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">结算管理</span>
          <div class="right-button">
            <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="handleAdd">
              新增结算单
            </el-button>
            <el-button type="warning" :icon="useRenderIcon(Download)" @click="handleExport">
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="结算单号" prop="billNo">
          <el-select
            v-model="queryParams.billNo"
            placeholder="请选择结算单号"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="option in billNoOptions"
              :key="option.billNo"
              :label="option.billNo"
              :value="option.billNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-tooltip content="系统将查询该项目下所有订单关联的结算单" placement="top">
            <el-select
              v-model="queryParams.projectId"
              placeholder="请选择项目"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="project in projectOptions"
                :key="project.projectId"
                :label="project.projectName"
                :value="project.projectId"
              />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结算时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="useRenderIcon(Refresh)" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="settlementList" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="结算单ID" align="center" width="90" />
        <el-table-column
          prop="billNo"
          label="结算单号"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="projectName" label="项目名称" align="center" min-width="120" />
        <el-table-column prop="orderNo" label="订单编号" align="center" min-width="120" />
        <el-table-column prop="supplierName" label="供应商" align="center" min-width="120" />
        <el-table-column prop="periodTypeDesc" label="结算周期" align="center" width="120" />
        <el-table-column
          prop="totalAmount"
          label="结算金额"
          align="center"
          width="120"
          :formatter="row => formatAmount(row.totalAmount)"
        />
        <el-table-column
          prop="startDate"
          label="开始日期"
          align="center"
          width="120"
          :formatter="row => formatDate(row.startDate)"
        />
        <el-table-column
          prop="endDate"
          label="结束日期"
          align="center"
          width="120"
          :formatter="row => formatDate(row.endDate)"
        />
        <el-table-column prop="status" label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusDesc || getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '0'"
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(EditPen)"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(View)"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              v-if="scope.row.status === '0'"
              link
              type="success"
              size="small"
              :icon="useRenderIcon(Check)"
              @click="handleSubmit(scope.row)"
              >提交</el-button
            >
            <el-popconfirm
              :title="`是否确认删除结算单'${scope.row.billNo}'?`"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button
                  v-if="scope.row.status === '0'"
                  link
                  type="danger"
                  size="small"
                  :icon="useRenderIcon(Delete)"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-block">
            <el-empty description="暂无结算单数据" />
            <div class="empty-tips">您可以点击"新增结算单"按钮添加结算单信息</div>
          </div>
        </template>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :currentPage="queryParams.pageNum"
        :pageSize="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 结算单表单组件 -->
    <SettlementForm
      v-if="dialog.visible && form"
      v-model="dialog.visible"
      :title="dialog.title"
      :settlement="form"
      @success="getList"
    />

    <!-- 结算单详情组件 -->
    <SettlementDetail
      v-if="detailDialog.visible && currentSettlement"
      v-model="detailDialog.visible"
      :settlement="currentSettlement"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessageBox, ElMessage, FormInstance } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/view";
import Delete from "@iconify-icons/ep/delete";
import Check from "@iconify-icons/ep/check";
import Download from "@iconify-icons/ep/download";
import { SettlementVO, SettlementQuery, SettlementStatus } from "@/types/attendance/settlement";
import {
  getSettlementList,
  getSettlementInfo,
  submitReview,
  deleteSettlement,
  exportSettlement,
  getBillNoOptions
} from "@/api/attendance/settlement";
import { getProjectOptions } from "@/api/attendance/order";
import SettlementForm from "./components/SettlementForm.vue";
import SettlementDetail from "./components/SettlementDetail.vue";

// 查询参数
const queryParams = reactive<SettlementQuery>({
  billNo: "",
  projectId: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10
});

// 日期范围
const dateRange = ref<[string, string] | null>(null);

// 查询引用
const queryRef = ref<FormInstance>();

// 状态选项
const statusOptions = [
  { value: SettlementStatus.DRAFT, label: "草稿" },
  { value: SettlementStatus.PARTY_B_PENDING, label: "待乙方审核" },
  { value: SettlementStatus.PARTY_B_APPROVED, label: "乙方已确认" },
  { value: SettlementStatus.PARTY_A_PENDING, label: "待甲方审核" },
  { value: SettlementStatus.COMPLETED, label: "已完成" },
  { value: SettlementStatus.CANCELLED, label: "已取消" }
];

// 项目选项
const projectOptions = ref([]);

// 结算单号选项
const billNoOptions = ref([]);

// 加载状态
const loading = ref(false);

// 结算单列表
const settlementList = ref<SettlementVO[]>([]);

// 总记录数
const total = ref(0);

// 对话框配置
const dialog = reactive({
  visible: false,
  title: ""
});

// 详情对话框配置
const detailDialog = reactive({
  visible: false
});

// 表单数据
const form = ref<SettlementVO>({
  id: undefined,
  billNo: undefined,
  projectId: undefined,
  orderId: undefined,
  supplierId: undefined,
  startDate: undefined,
  endDate: undefined,
  totalAmount: 0,
  status: undefined,
  remark: undefined,
  details: []
});

// 当前选中的结算单
const currentSettlement = ref<SettlementVO>({
  id: undefined,
  billNo: undefined,
  projectId: undefined,
  orderId: undefined,
  supplierId: undefined,
  startDate: undefined,
  endDate: undefined,
  totalAmount: 0,
  status: undefined,
  remark: undefined,
  details: []
});

// 页面加载时获取列表
onMounted(() => {
  getList();
  getOptions();
});

// 监听日期范围变化
watch(dateRange, newVal => {
  if (newVal) {
    queryParams.startDate = newVal[0];
    queryParams.endDate = newVal[1];
  } else {
    queryParams.startDate = undefined;
    queryParams.endDate = undefined;
  }
});

// 获取项目和结算单号选项
const getOptions = async () => {
  try {
    // 获取项目选项
    const projectRes = await getProjectOptions();
    projectOptions.value = projectRes.data || [];

    // 获取结算单号选项
    const billNoRes = await getBillNoOptions();
    billNoOptions.value = billNoRes.data || [];
  } catch (error) {
    console.error("获取选项数据失败", error);
  }
};

// 获取结算单列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getSettlementList(queryParams);
    settlementList.value = res.data.rows;
    total.value = res.data.total;
  } catch (error) {
    console.error("获取结算单列表失败", error);
  } finally {
    loading.value = false;
  }
};

// 格式化金额
const formatAmount = (amount: number | undefined) => {
  if (amount === undefined || amount === null) {
    return "¥0.00";
  }
  return amount.toLocaleString("zh-CN", {
    style: "currency",
    currency: "CNY",
    minimumFractionDigits: 2
  });
};

// 格式化日期
const formatDate = (date: string | undefined) => {
  if (!date) return "-";
  return date.split(" ")[0]; // 只显示日期部分
};

// 获取状态样式
const getStatusType = (status: string | undefined) => {
  if (!status) return "";
  switch (status) {
    case SettlementStatus.DRAFT:
      return "info";
    case SettlementStatus.PARTY_B_PENDING:
    case SettlementStatus.PARTY_A_PENDING:
      return "warning";
    case SettlementStatus.PARTY_B_APPROVED:
      return "success";
    case SettlementStatus.COMPLETED:
      return "success";
    case SettlementStatus.CANCELLED:
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: string | undefined) => {
  if (!status) return "未知状态";
  const option = statusOptions.find(item => item.value === status);
  return option ? option.label : "未知状态";
};

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryRef.value?.resetFields();
  dateRange.value = null;
  queryParams.startDate = undefined;
  queryParams.endDate = undefined;
  queryParams.pageNum = 1;
  getList();
};

// 每页数量变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getList();
};

// 页码变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getList();
};

// 新增结算单
const handleAdd = () => {
  form.value = {
    id: undefined,
    billNo: undefined,
    projectId: undefined,
    orderId: undefined,
    supplierId: undefined,
    startDate: undefined,
    endDate: undefined,
    totalAmount: 0,
    status: SettlementStatus.DRAFT,
    remark: undefined,
    details: []
  } as SettlementVO;
  dialog.title = "新增结算单";
  dialog.visible = true;
};

// 修改结算单
const handleUpdate = (row: SettlementVO) => {
  if (!row || !row.id) {
    ElMessage.error("结算单数据不完整");
    return;
  }

  dialog.title = "修改结算单";
  loading.value = true;

  getSettlementInfo(row.id)
    .then(res => {
      if (res.data) {
        form.value = JSON.parse(JSON.stringify(res.data)); // 深拷贝数据，避免引用问题
        setTimeout(() => {
          dialog.visible = true;
          loading.value = false;
        }, 100); // 增加短暂延时，确保数据完全加载
      } else {
        ElMessage.error("获取结算单详情数据为空");
        loading.value = false;
      }
    })
    .catch(error => {
      console.error("获取结算单详情失败", error);
      ElMessage.error("获取结算单详情失败");
      loading.value = false;
    });
};

// 查看结算单
const handleView = (row: SettlementVO) => {
  // 确保id有值
  if (!row.id) {
    console.error("结算单ID不存在", row);
    ElMessage.error("结算单ID不存在");
    return;
  }

  loading.value = true;

  getSettlementInfo(row.id)
    .then(res => {
      if (res.data) {
        currentSettlement.value = JSON.parse(JSON.stringify(res.data)); // 深拷贝数据
        setTimeout(() => {
          detailDialog.visible = true;
          loading.value = false;
        }, 100); // 确保数据完全加载
      } else {
        ElMessage.error("获取结算单详情数据为空");
        loading.value = false;
      }
    })
    .catch(error => {
      console.error("获取结算单详情失败", error);
      ElMessage.error("获取结算单详情失败");
      loading.value = false;
    });
};

// 删除结算单
const handleDelete = (row: SettlementVO) => {
  loading.value = true;
  deleteSettlement(row.id as number)
    .then(() => {
      ElMessage.success("删除成功");
      getList();
    })
    .catch(error => {
      console.error("删除结算单失败", error);
      ElMessage.error("删除结算单失败");
      loading.value = false;
    });
};

// 提交审核
const handleSubmit = (row: SettlementVO) => {
  ElMessageBox.confirm(`是否确认提交结算单"${row.billNo}"进行审核?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      loading.value = true;
      submitReview(row.id as number)
        .then(() => {
          ElMessage.success("提交成功");
          getList();
        })
        .catch(error => {
          console.error("提交审核失败", error);
          ElMessage.error("提交审核失败");
          loading.value = false;
        });
    })
    .catch(() => {});
};

// 导出结算单
const handleExport = () => {
  exportSettlement(queryParams)
    .then(res => {
      const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
      const fileName = `结算单_${new Date().getTime()}.xlsx`;
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(link.href);
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
.settlement-container {
  padding: 10px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: bold;
    }

    .right-button {
      display: flex;
      gap: 10px;
    }
  }

  .el-form {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .empty-block {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;

    .empty-tips {
      margin-top: 10px;
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>
